<template>
  <div class="">
    <div :id="chartId" class="chart"></div>
  </div>
</template>

<script>
import * as echarts from "echarts";
export default {
  data() {
    return {};
  },
  props: ["chartId", "datas"],
  created(){
    this.$nextTick(()=>{
      this.$watch('datas',()=>{
        this.initChart();
      })
    })
  },
  mounted() {
    this.initChart();
  },
  methods: {
    initChart() {
      let myChart = echarts.init(document.getElementById(this.chartId));
      var series = [];
      var colorStops = [
        [
          {
            offset: 0.1,
            color: "#26D8FF", // 100% 处的颜色
          },
          {
            offset: 1,
            color: "#1A7DF2", // 0% 处的颜色
          },
        ],
        [
          {
            offset: 0.1,
            color: "#1AFEF9", // 0% 处的颜色
          },
          {
            offset: 1,
            color: "#27FFAF", // 100% 处的颜色
          },
        ],
      ];
      for (let i = 0; i < this.datas.legendData.length; i++) {
        let obj = {
          name: this.datas.legendData[i],
          type: "bar",
          barWidth: 10,
          itemStyle: {
            color: {
              type: "linear",
              x: 0, //右
              y: 0, //下
              x2: 1, //左
              y2: 1, //上
              colorStops: colorStops[i],
            },
          },
          data: this.datas.data[i],
          label: {
            //数据显示的位置
            show: true, //数值是否显示
            position: "top",
            textStyle: {
              color: "#FFFFFF", // 标签字体颜色
              fontSize: 12, // 标签字体大小
            },
          },
        };
        series.push(obj);
      }
      // 绘制图表
      myChart.setOption({
        legend: {
          show: false,
          textStyle: {
            color: "#FFFFFF",
          },
          itemWidth: 15,
          itemHeight: 15,
          right: 15,
          top: 15,
          itemGap: 50,
        },
        grid: {
          left: "8%",
          top: "10%",
          right: "5%",
          bottom: "18%",
        },
        xAxis: {
          axisLine: {
            show: true,
          },
          axisLabel: {
            color: "#FFFFFF",
          },
          axisTick: {
            show: false,
          },
          data: this.datas.xPoint,
        },
        yAxis: [
          {
            type: "value",
            splitLine: {
              show: true,
              lineStyle: {
                type: "dashed",
                color: "rgba(16, 100, 109, 0.2)",
              },
            },
            axisLine: { show: false },
            axisLabel: {
              color: "#FFFFFF",
            },
            offset: -5,
          },
        ],
        series,
      });

      window.onresize = function () {
        // 自适应大小
        myChart.resize();
      };
    },
  },
};
</script>
<style scoped lang="scss">
.chart {
  height: 260px;
}
</style>
